/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "dma.h"
#include "fdcan.h"
#include "memorymap.h"
#include "spi.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include <string.h>
#include "BMI088driver.h"
#include "bsp_fdcan.h"
#include <stdbool.h>
#include "uart_sbus.h"
#include "stdio.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
#define U2_RX_LEN   6
#define U3_RX_LEN   6

uint8_t u2Rx[U2_RX_LEN];
uint8_t u3Rx[U3_RX_LEN];

//uint8_t u2RxFlag = 0;
//uint8_t u3RxFlag = 0;

uint8_t tx_data[8] = {0,1,2,3,4,5,6,7};
uint8_t rx_data[8];
uint16_t received_id;
//adc
float GetVoltageOnPC4(void)
{
  float adcValue = 0;
  float voltage = 0;
  if (HAL_ADC_Start(&hadc1) != HAL_OK)
  {
    Error_Handler();
  }
  if (HAL_ADC_PollForConversion(&hadc1, 100) == HAL_OK)
  {
    adcValue = HAL_ADC_GetValue(&hadc1);
  }
  else
  {
    Error_Handler();
  }
  if (HAL_ADC_Stop(&hadc1) != HAL_OK)
  {
    Error_Handler();
  }

	voltage =(adcValue*2.5f/65535)*21.0f;
	
  return voltage;
}
//485
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
    if (huart == &huart2)
    {
			printf("485 huart2\n");
      HAL_UART_Receive_IT(&huart2, u2Rx, U2_RX_LEN);
    }
    if (huart == &huart3)
    {
			printf("485 huart3\n");
      HAL_UART_Receive_IT(&huart3, u3Rx, U3_RX_LEN);
    }
}
//sbus
void SBUS_init(void)
{
  HAL_UARTEx_ReceiveToIdle_DMA(&huart4, rx_buff, BUFF_SIZE );
  __HAL_UART_ENABLE_IT(&huart4, UART_IT_IDLE); 
}
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
float vbus;
float gyro[3], accel[3], temp;
uint8_t dma_rx_complete = 0;
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_SPI2_Init();
  MX_USART1_UART_Init();
  MX_USART2_UART_Init();
  MX_USART3_UART_Init();
  MX_ADC1_Init();
  MX_FDCAN1_Init();
  MX_FDCAN2_Init();
  MX_UART4_Init();
  /* USER CODE BEGIN 2 */
	HAL_UART_Receive_IT(&huart2, u2Rx, U2_RX_LEN);
  HAL_UART_Receive_IT(&huart3, u3Rx, U3_RX_LEN);
	bsp_can_init();

		while(BMI088_init())
	{
		;
	}
	SBUS_init();
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
		static uint32_t ledTimer = 0;
		static uint32_t uartTimer = 0;
    static uint32_t rs485Timer = 0;
    static uint32_t canTimer = 0;
    static uint32_t adcTimer = 0;
    static uint32_t imuTimer = 0;
    uint32_t currentTime = HAL_GetTick();

    if (currentTime - ledTimer >= 500) {
        ledTimer = currentTime;
			//LED
        HAL_GPIO_TogglePin(GPIOE, GPIO_PIN_2);
        HAL_GPIO_TogglePin(GPIOE, GPIO_PIN_3);
    }
		if (currentTime - uartTimer >= 500) {
        uartTimer = currentTime;
			//CTRL
				HAL_GPIO_WritePin(GPIOB,GPIO_PIN_6,SET);
				HAL_GPIO_WritePin(GPIOB,GPIO_PIN_6,SET);
			//bluetooth
				HAL_GPIO_WritePin(GPIOC,GPIO_PIN_12,SET);
				HAL_GPIO_WritePin(GPIOD,GPIO_PIN_2,SET);
			//BEEF_CRTL
				HAL_GPIO_WritePin(GPIOE,GPIO_PIN_8,SET);
			//ADC_POWER_OUT
				HAL_GPIO_WritePin(GPIOC,GPIO_PIN_5,SET);
			//POWER_OUT_EN
				HAL_GPIO_WritePin(GPIOE,GPIO_PIN_12,SET);
			//PRE_CHARGING_EN
				HAL_GPIO_WritePin(GPIOE,GPIO_PIN_13,SET);
    }
		if (currentTime - rs485Timer >= 100) {
        rs485Timer = currentTime;
			//485
        HAL_UART_Transmit(&huart2, "huart2\n", strlen("huart2\n"), 100);
        HAL_UART_Transmit(&huart3, "huart3\n", strlen("huart3\n"), 100);
    }
		// CAN
    if (currentTime - canTimer >= 20) {
        canTimer = currentTime;
        fdcanx_send_data(&hfdcan1, 0x555, tx_data, 8);
        fdcanx_send_data(&hfdcan2, 0x555, tx_data, 8);
				printf("fdcan send\n");
    }

    // ADC
    if (currentTime - adcTimer >= 100) {
        adcTimer = currentTime;
        vbus = GetVoltageOnPC4();
    }
		printf("ADC vbus:%.2f\n",vbus);

    // IMU�
    if (currentTime - imuTimer >= 100) {
        imuTimer = currentTime;
        BMI088_read(gyro, accel, &temp);
    }
		printf("gyro x = %.2f  y = %.2f  z = %.2f\n",gyro[0],gyro[1],gyro[2]);
		printf("accel x = %.2f  y = %.2f  z = %.2f\n",accel[0],accel[1],accel[2]);
		printf("temp = %.2f\n",temp);
		HAL_Delay(1000);
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Supply configuration update enable
  */
  HAL_PWREx_ConfigSupply(PWR_LDO_SUPPLY);

  /** Configure the main internal regulator output voltage
  */
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE0);

  while(!__HAL_PWR_GET_FLAG(PWR_FLAG_VOSRDY)) {}

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = 2;
  RCC_OscInitStruct.PLL.PLLN = 40;
  RCC_OscInitStruct.PLL.PLLP = 1;
  RCC_OscInitStruct.PLL.PLLQ = 6;
  RCC_OscInitStruct.PLL.PLLR = 2;
  RCC_OscInitStruct.PLL.PLLRGE = RCC_PLL1VCIRANGE_3;
  RCC_OscInitStruct.PLL.PLLVCOSEL = RCC_PLL1VCOWIDE;
  RCC_OscInitStruct.PLL.PLLFRACN = 0;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2
                              |RCC_CLOCKTYPE_D3PCLK1|RCC_CLOCKTYPE_D1PCLK1;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.SYSCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB3CLKDivider = RCC_APB3_DIV2;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_APB1_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_APB2_DIV2;
  RCC_ClkInitStruct.APB4CLKDivider = RCC_APB4_DIV2;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_3) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
